package com.gaojinqi.service.impl;

import com.gaojinqi.exception.SellException;
import com.gaojinqi.service.RedisLockService;
import com.gaojinqi.service.SecKillService;
import com.gaojinqi.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author gaojinqi
 * @date 2019/5/13 1:39
 */
@Slf4j
@Service
public class SecKillServiceImpl implements SecKillService {

    // 超时时间
    public static final int TIMEOUT = 10 * 1000;

    @Autowired
    private RedisLockService redisLockService;

    /**
     * 双11活动，三只松鼠秒杀，限量100000份
     */
    // 商品
    static Map<String, Integer> products;
    // 库存
    static Map<String, Integer> stock;
    // 订单
    static Map<String, String> orders;

    static {
        /**
         * 模拟假数据
         */
        products = new HashMap<>();
        stock = new HashMap<>();
        orders = new HashMap<>();
        products.put("123456", 100000);
        stock.put("123456", 100000);
    }

    private String queryMap(String productId) {
        return "双十一活动，三只松鼠秒杀，限量" + products.get(productId) + "份" +
                " 还剩：" + stock.get(productId) + "份" +
                " 该商品成功下单用户数目：" + orders.size() + "人";
    }

    @Override
    public String querySecKillProductInfo(String productId) {
        return this.queryMap(productId);
    }

    @Override
    public void orderProdictMockDiffUser(String productId) {
        // 加锁
        long time = System.currentTimeMillis() + TIMEOUT;
        if (!redisLockService.lock(productId, String.valueOf(time))) {
            throw new SellException(101, "哎呦喂，人太多了，请稍后重试~");
        }

        // 1.查询该商品库存，为0则活动结束
        Integer stockNum = stock.get(productId);
        if (stockNum == 0) {
            throw new SellException(100, "活动结束");
        } else {
            // 2.下单（模拟不同用户openid不同）
            orders.put(KeyUtil.genUniqueKey(), productId);
            // 3.减库存
            stockNum = stockNum - 1;
            try {
                // 模拟业务逻辑耗时
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            stock.put(productId, stockNum);
        }

        // 解锁
        redisLockService.unlock(productId, String.valueOf(time));
    }
}
